package com.test.jwtlogin.aspect;


import com.test.jwtlogin.exception.ServiceRuntimeException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

@Aspect
@Component
public class NotDuplicateAspect {
    private static final Set<String> KEY = new ConcurrentSkipListSet<>();

    @Pointcut("@annotation(com.test.jwtlogin.annotation.NotDuplicate)")
    public void duplicate() {
    }
    @Around("duplicate()")
    public Object duplicate(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature msig = (MethodSignature) joinPoint.getSignature();
        Method currentMethod = joinPoint.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());
        StringBuffer sb = new StringBuffer(currentMethod.toString());
        Object[] args = joinPoint.getArgs();
        for (Object object : args) {
            if (object != null) {
                sb.append(object.getClass().toString());
                sb.append(object.toString());
            }
        }
        String sign = sb.toString();
        boolean success = KEY.add(sign);
        if (!success) {
            throw new ServiceRuntimeException("该方法正在执行，不能重复请求");
        }
        try {
            return joinPoint.proceed();
        }finally {
            KEY.remove(sign);
        }

    }
}
